<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;
use app\api\error\Money as MoneyError;
use app\api\error\Common as CommonError;
/**
 * MDC接口逻辑
 */
class Money extends ApiBase
{
	/**
     * 转让记录
     */
    public function zrMoneylist($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		if($data['is'] == 1){
			$where=" user_id=".$data['user_id'];
		}else{
			$where=" getid=".$data['user_id'];
		}
		$list=db('money_zr')->where($where)->limit($page,$list_rows)->order("id desc")->select();
		foreach($list as $k=>$v){
			if($data['is'] == 1){
				$list[$k]['username']=db('user')->where('id',$v['getid'])->value('username');
			}else{
				$list[$k]['username']=db('user')->where('id',$v['user_id'])->value('username');
			}
		}
		return $list;		
	}
	/**
     * MDC列表
     */
    public function cjOrderList($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" user_id=".$data['user_id']." and cid=".$data['cid'];
		$list=db('cj_order')->where($where)->limit($page,$list_rows)->order("id desc")->select();
		/*foreach($list as $k=>$v){
			$list[$k]['msg']=moneyType($v['type']);
		}*/
		return $list;		
	}
	/**
     * 竞猜下单
     */
	public function cjOrder($data){
		$max=config('cjConfig');
		$num=db('cj_order')->where('cid',$data['cid'])->count();
		if($num >= $max){
			return MoneyError::$cjOrderError;
		}
		
		$cinfo=db('cj')->where('id',$data['cid'])->find();
		if(empty($cinfo)){
			return MoneyError::$paramError;
		}
		if(strtotime($cinfo['start_time']) > time() || strtotime($cinfo['end_time']) < time()){
			return MoneyError::$paramError;
		}
		$info=db('user')->field('password,moneyMy,salt')->where('id',$data['user_id'])->find();
		if (data_md5_key($data['password'],$info['salt']) !== $info['password']) {            
			return MoneyError::$payPasswordError;
		}
		$money_id=db('money')->where(array('user_id'=>$data['user_id'],'status'=>1,'isys'=>1,'is'=>0))->order('id asc')->value('id');
		if(empty($money_id)){
			return MoneyError::$zrMoneyError;
		}
		$data['money_id']=$money_id;
		$data['create_time']=time();	
		db('cj_order')->startTrans();
		$res=db('cj_order')->insert($data);
		$re=money_log(10001,6,$data['user_id'],$money_id);			
		if($res && $re ){
			db('cj_order')->commit();
			return $this->apiReturn();
		}else{
			db('cj_order')->rollback();
			return  MoneyError::$confirmFail;
		}		
	}
	/**
     * uDC兑换
     */
	public function udcChange($data){
		$username=db('user')->where('id',$data['user_id'])->value('username');
		if( $msg = checkEmail($username,$data['code'])){
			return $msg;
		}
		if(!empty($data['type'])){
			$count=db('money')->where(array('user_id'=>$data['user_id'],'status'=>1,'is'=>0,'isys'=>1))->count();
			if($count < $data['num']){
				return MoneyError::$zrMoneyError;
			}
			$arr = db('money')->field('id')->where(array('user_id'=>$data['user_id'],'status'=>1,'is'=>0,'isys'=>1))->limit($data['num'])->select();
			$data['create_time']=time();
			$data['money']=$data['num']*0.9;
			db('udc_change')->startTrans();
			$r = db('udc_change')->insert($data);
			$re = moneyyj_log($data['money'],$data['user_id'],10,$data['user_id']);
			foreach($arr as $v){
				$res=money_log(10001,6,$data['user_id'],$v['id']);
				if($res == false){
					db('udc_change')->rollback();
					return MoneyError::$paramError;
				}
			}
		}else{
			$arr = explode(',',$data['ids']);
			$data['num']=count($arr);
			$data['create_time']=time();
			$data['money']=$data['num']*0.9;
			$r = db('udc_change')->insert($data);
			$re = moneyyj_log($data['money'],$data['user_id'],10,$data['user_id']);			
			foreach($arr as $v){
				$res=money_log(10001,6,$data['user_id'],$v);
				if($res == false){
					db('udc_change')->rollback();
					return MoneyError::$paramError;
				}
			}
		}
					
		
		if($res && $re && $r){
			db('udc_change')->commit();
			return $this->apiReturn();	
		}else{
			db('udc_change')->rollback();
			return MoneyError::$paramError;
		}
		
	}
	/**
     * 转让MDC
     */
	public function zrMoneys($data){
		$userid=db('user')->where('username',$data['username'])->value('id');
		if(empty($userid)){
			return MoneyError::$paramError;
		}
		$count=db('money')->where(array('user_id'=>$data['user_id'],'status'=>1,'is'=>0,'isys'=>1))->count();
		if($count < $data['num']){
			return MoneyError::$zrMoneyError;
		}
		$username=db('user')->where('id',$data['user_id'])->value('username');
		if( $msg = checkEmail($username,$data['code'])){
			return $msg;
		}	
		$arr = db('money')->field('id')->where(array('user_id'=>$data['user_id'],'status'=>1,'is'=>0,'isys'=>1))->limit($data['num'])->select();	
		
		db('money_log')->startTrans();
		$arrs=array(
			'user_id'=>$data['user_id'],
			'getid'=>$userid,
			'num'=>count($arr),
			'create_time'=>time(),
			'beizhu'=>$data['beizhu']
		);
		db('money_zr')->insert($arrs);
		foreach($arr as $v){
			$res=money_log($userid,4,$data['user_id'],$v['id']);
			if($res == false){
				db('money_zr')->rollback();
				return MoneyError::$paramError;
			}
		}
		if($res != false){
			db('money_zr')->commit();
			return $this->apiReturn();	
		}
	}
	/**
     * 锁定MDC
     */
	public function opUdc($data){
		$res=db('money')->where(array('id'=>$data['money_id'],'user_id'=>$data['user_id']))->update(array('status'=>$data['status']));
		if(!empty($res)){
			return $this->apiReturn();
		}else{
			return  MoneyError::$paramError;
		}	
	}
	/**
     * 批量购买MDC
     */
	public function buyMoneys($data){
		$arr=parse_config_array('udc_zk');
		if($arr['num'] > $data['num']){
			return MoneyError::$paramError;
		}
		$count=db('money')->where('user_id',10000)->count();
		if($count < $data['num']){
			return MoneyError::$numError;
		}
		$dj=config('mdc_money');
		$price=$dj*$data['num']*$arr['zk'];
		//if($data['num'] > $count){
		//	return MoneyError::$numError;
		//}
		if($data['pay'] == 1){
			$info=db('user')->field('password,moneyMy,salt')->where('id',$data['user_id'])->find();
			if (data_md5_key($data['password'],$info['salt']) !== $info['password']) {            
				return MoneyError::$payPasswordError;
			}
			if($info['moneyMy'] < $price){
				return MoneyError::$moneyError;
			}
		}
		if(!empty($data['is'])){
			$str=$data['is']==1?'1':'2';
		}else{
			$str='1';
		}
		$order_sn='mc'.$str.date('ymdhis').rand(1,9);
		$arr=array(
			'order_sn'=>$order_sn,
			'user_id'=>$data['user_id'],
			'money'=>$price,
			'dj'=>$dj,
			'num'=>$data['num'],
			'pay'=>$data['pay'],
			'stat'=>0,
			'zk'=>$arr['zk'],
			'create_time'=>time()
		);
		db('money_order')->startTrans();
		$res=db('money_order')->insert($arr);
		if($data['pay'] == 1){
			$re = moneyyj_log((-1)*$price,$data['user_id'],2,$data['user_id']);
			$r=getBuyMDC($order_sn);
		}else{
			$re = true;
			$r = true;
		}			
		if($res && $re && $r){
			db('money_order')->commit();
			return array('order_sn'=>$order_sn);
		}else{
			db('money_order')->rollback();
			return  MoneyError::$confirmFail;
		}		
	}
	/**
     * MDC配置信息
     */
    public function mdcConfig(){
		$arr=array(
			'money'=>config('mdc_money'),
			'num'=>config('mdc_num'),
			'share'=>config('mdc_share'),
			'change'=>config('udc_change')
		);
		return $arr;		
	}
    /**
     * MDC列表
     */
    public function getMoneyList($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		//$where=" `is`=0 and status =1 and user_id=".$data['user_id'];
		$where=" user_id=".$data['user_id'];
		if(isset($data['is'])){
			$where.=" and `is`=".$data['is'];
		}
		if(isset($data['status'])){
			$where.=" and status=".$data['status'];
		}
		if(isset($data['isys'])){
			$where.=" and isys=".$data['isys'];
		}
		if(!empty($data['keywords'])){
			$keywords=$data['keywords'];
			$where.=" and code like '%$keywords%'";
		}
		$list=db('money')->where($where)->limit($page,$list_rows)->order(" status asc,isys asc,create_time desc,id desc")->select();
		foreach($list as $k=>$v){
			$list[$k]['msg']=moneyType($v['type']);
		}
		return $list;		
	}
	/**
     * MDC出售列表
     */
    public function sellMoneyLog($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		if(!empty($data['user_id'])){
			$where=array('stat'=>0,'user_id'=>$data['user_id']);
		}else{
			$where=array('stat'=>0);
		}
		$count=db('sell')->where($where)->count();
		$list=db('sell')->where($where)->limit($page,$list_rows)->order("id Asc")->select();
		$counts=array('count'=>$count);
		foreach($list as $k=>$v){
			$list[$k]['moneyInfo']=db('money')->where('id',$v['money_id'])->find();
		}
		return compact('list','counts');		
	}
	 /**
     * MDC挂卖
     */
    public function sellMoney($data){
		$arr = explode(',',$data['ids']);
		db('money')->startTrans();
		foreach($arr as $v){
			$is=db('money')->where(array('status'=>1,'id'=>$v,'user_id'=>$data['user_id']))->value('id');
			if(empty($is)){
				return MoneyError::$paramError;
			}
			$issell=db('sell')->where(array('stat'=>0,'money_id'=>$v,'user_id'=>$data['user_id']))->value('id');
			
			if(!empty($issell)){
				$res=db('sell')->where('id',$issell)->update(array('create_time'=>time(),'stat'=>0));
			}else{
				$data['create_time']=time();
				$data['money_id']=$v;
				$res=db('sell')->insertGetId($data);				
			}
			$re=db('money')->where('id',$v)->update(array('is'=>1));		
		}	
		if ($res && $re){			
			db('money')->commit();
			return $this->apiReturn();	
		}else{
			db('money')->rollback();
			return MoneyError::$confirmFail;
		}
	}
	 /**
     * 撤销MDC挂卖
     */
    public function revokeMoneys($data){
		$arr=db('sell')->where(array('stat'=>0,'user_id'=>$data['user_id']))->limit($data['num'])->column('money_id');
		if(count($arr)<$data['num']){
			return MoneyError::$paramError;
		}
		db('money')->startTrans();
		foreach($arr as $v){
			$res=db('sell')->where('id',$is)->delete();
			$re=db('money')->where('id',$v)->update(array('is'=>0));
		}	
		if ($res && $re) {
			db('money')->commit();
			return $this->apiReturn();	
		}else{
			db('money')->rollback();
			return MoneyError::$confirmFail;
		}
	}
	 /**
     * 撤销MDC挂卖
     */
    public function revokeMoney($data){
		$arr = explode(',',$data['ids']);
		db('money')->startTrans();
		foreach($arr as $v){
			$is=db('sell')->where(array('money_id'=>$v,'user_id'=>$data['user_id']))->value('id');
			if(empty($is)){
				return MoneyError::$paramError;
			}
			$res=db('sell')->where('id',$is)->delete();
			$re=db('money')->where('id',$v)->update(array('is'=>0));
		}	
		if ($res && $re) {
			db('money')->commit();
			return $this->apiReturn();	
		}else{
			db('money')->rollback();
			return MoneyError::$confirmFail;
		}
	}
	/**
     * 转让MDC
     */
	public function zrMoney($data){
		$userid=db('user')->where('username',$data['username'])->value('id');
		if(empty($userid)){
			return MoneyError::$paramError;
		}
		$username=db('user')->where('id',$data['user_id'])->value('username');
		
		if( $msg = checkEmail($username,$data['code'])){
			return $msg;
		}
		$arr = explode(',',$data['ids']);
		$arrs=array(
			'user_id'=>$data['user_id'],
			'getid'=>$userid,
			'num'=>count($arr),
			'create_time'=>time(),
			'beizhu'=>$data['beizhu']
		);
		db('money_log')->startTrans();
		db('money_zr')->insert($arrs);
		foreach($arr as $v){
			$res=money_log($userid,4,$data['user_id'],$v);
			if($res == false){
				db('money_log')->rollback();
				return MoneyError::$paramError;
			}
		}
		if($res != false){
			db('money_log')->commit();
			return $this->apiReturn();	
		}else{
			db('money_log')->rollback();
			return MoneyError::$paramError;
		}
		
	}
	/**
     * 购买MDC
     */
	public function buyMoney($data){
		$count=db('sell')->where('stat',0)->count();
		$dj=config('mdc_money');
		$price=$dj*$data['num'];
		if($data['num'] > $count){
			return MoneyError::$numError;
		}
		if($data['pay'] == 1){
			$info=db('user')->field('password,moneyMy,salt')->where('id',$data['user_id'])->find();
			if (data_md5_key($data['password'],$info['salt']) !== $info['password']) {            
				return MoneyError::$payPasswordError;
			}
			if($info['moneyMy'] < $price){
				return MoneyError::$moneyError;
			}
		}
		if(!empty($data['is'])){
			$str=$data['is']==1?'1':'2';
		}else{
			$str='1';
		}
		$order_sn='mc'.$str.date('ymdhis').rand(1,9);
		$arr=array(
			'order_sn'=>$order_sn,
			'user_id'=>$data['user_id'],
			'money'=>$price,
			'dj'=>$dj,
			'num'=>$data['num'],
			'pay'=>$data['pay'],
			'stat'=>0,
			'create_time'=>time()
		);
		db('money_order')->startTrans();
		$res=db('money_order')->insert($arr);
		if($data['pay'] == 1){
			$re = moneyyj_log((-1)*$price,$data['user_id'],2,$data['user_id']);
			$r=getMDC($order_sn);
		}else{
			$re = true;
			$r = true;
		}			
		if($res && $re && $r){
			db('money_order')->commit();
			return array('order_sn'=>$order_sn);
		}else{
			db('money_order')->rollback();
			return  MoneyError::$confirmFail;
		}		
	}
	
	/**
     * 成交MDC列表（购买/转让）
     */
    public function finishList($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" (type=3 or type=4) and getid=".$data['user_id'];
		$list=db('money_log')->where($where)->limit($page,$list_rows)->order("id desc")->select();
		foreach($list as $k=>$v){
			$list[$k]['moneyInfo']=db('money')->where('id',$v['money_id'])->find();
		}
		return $list;	
	}
	/**
     * 兑换规则
     */
    public function dhConfig($data){
		$arr=parse_config_array('exchange_mdc');
		return $arr;
	}
	/**
     * 兑换权限
     */
    public function exchangeNum($data){
		$list=explode(',',$data['ids']);
		db('company')->startTrans();
		foreach($list as $v){
			if($str=is_checkMoneys(6,$v,$data['user_id'])){		
				return ['code' => 1030002, 'msg' => $str];
				//return MoneyError::$confirmFail;
			}else{
				$re=money_log(10001,6,$data['user_id'],$v);
				$arr=parse_config_array('exchange_mdc');	
				if( $data['type'] == 0 ){
					//$res=db('company')->where(array('user_id'=>$data['user_id'],'stat'=>1))->setInc('workNum',intval($arr['fb']));
					$res=logAdd($data['user_id'],$data['user_id'],0,'mdc兑换',intval($arr['fb']),2);
				}else{
					$res=logAdd($data['user_id'],$data['user_id'],1,'mdc兑换',intval($arr['ck']),2);
					//$res=db('company')->where(array('user_id'=>$data['user_id'],'stat'=>1))->setInc('resumeNum',intval($arr['ck']));
				}
			}			
		}		
		if(!$res && $re){
			db('company')->commit();
			return $this->apiReturn();
		}else{
			db('company')->rollback();
			return  MoneyError::$confirmFail;
		}	
	}
	/**
     * mdc收支明细
     */
    public function moneyLogList($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" user_id=".$data['user_id']." or getid=".$data['user_id'];
		$list=db('money_log')->where($where)->limit($page,$list_rows)->order("create_time desc")->select();
		foreach($list as $k=>$v){
			$list[$k]['code']='M'.str_pad($v['money_id'],8,"0",STR_PAD_LEFT);
			if($v['user_id'] == $data['user_id']){
				$list[$k]['sz']=0;
				$list[$k]['msg']=moneyType($v['type']);
			}else{
				$list[$k]['sz']=1;
				if($v['type'] == 4){
					$list[$k]['msg']='转让给用户扣除';
				}elseif($v['type'] == 3 ){
					$list[$k]['msg']='挂卖成交扣除';
				}else{
					$list[$k]['msg']='兑换权限扣除';
				}
			}			
		}
		return $list;		
	}
	/**
	 * 购买套餐
	 */
	public function buySeries($data){
		$series=db('series')->where('id',$data['sid'])->find();
		if(empty($series)){
			return MoneyError::$paramError;
		}
		$price=$series['money'];
		if($data['pay'] == 1){
			$info=db('user')->field('password,moneyMy,salt')->where('id',$data['user_id'])->find();
			if (data_md5_key($data['password'],$info['salt']) !== $info['password']) {
				return MoneyError::$payPasswordError;
			}
			if($info['moneyMy'] < $price){
				return MoneyError::$moneyError;
			}
		}
		$order_sn='ms'.date('ymdhis').rand(10,99);
		$arr=array(
			'order_sn'=>$order_sn,
			'user_id'=>$data['user_id'],
			'money'=>$price,
			'sid'=>$data['sid'],
			'name'=>$series['name'],
			'month'=>$series['year'],
			'workNum'=>$series['workNum'],
			'resumeNum'=>$series['resumeNum'],
			'pay'=>$data['pay'],
			'stat'=>0,
			'create_time'=>time()
		);
		db('series_order')->startTrans();
		$res=db('series_order')->insert($arr);
		if($data['pay'] == 1){
			$r=getSeries($order_sn);
		}else{
			$r = true;
		}
		if($res && $r){
			db('series_order')->commit();
			return array('order_sn'=>$order_sn);
		}else{
			db('series_order')->rollback();
			return  MoneyError::$confirmFail;
		}
	}
	/**
	 * 套餐列表
	 */
	public function serieList($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" status =1  ";
		$list=db('series')->where($where)->limit($page,$list_rows)->order("sort desc")->select();
		return $list;
	}
	/**
	 * 套餐列表
	 */
	public function mySeries($data){
		$datas=array();
		$where=" stat = 1 and user_id=".$data['user_id'];
		$datas['seriesList']=db('series_order')->where($where)->order("id asc")->select();
		$datas['info']=db('company')->field('resume,work,end_time')->where('user_id',$data['user_id'])->find();
		return $datas;
	}
	/**
	 * 过期套餐列表
	 */
	public function overSeries($data){
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" stat = 2 and user_id=".$data['user_id'];
		$list=db('series_order')->where($where)->limit($page,$list_rows)->order("id desc")->select();
		return $list;
	}
}
